/**
 * 封装 axios app内http请求
 */

import axios from 'axios';
import api_config from '../config/api_config'
import config from '../config/config';
import token from '../libs/token';


const ajax_axios = axios.create(
    config.axios
);

const ajax = function (api_name, ddd = {}, callback_success = false, error_callback = false) {
    let config = apiconfig(api_name);

    if (error_callback == false) {
        error_callback = error;
    }

    if (callback_success == false) {
        callback_success = success;
    }
    if (config == false) {
        error_callback('config-error');
    }

    let headers = {};
        
    let AUTH_TOKEN = token.get();

    if (AUTH_TOKEN && config['token']) {
        headers.Authorized = AUTH_TOKEN;
    }


    let params = {};
    if (config.method == 'get') {
        params = ddd;
    }
    let callback_success2;
    if(typeof config.interceptors == 'function'){
        //存在拦截器
        callback_success2=function (res) {
            return callback_success(config.interceptors(res));
        };
    }else{
        callback_success2 = callback_success;
    }
    console.log('ajax->:',
        {
            'config': config,
            'data': ddd,
            'header': headers,
            'callback_success2':callback_success2,
            'error_callback':error_callback
        });
    ajax_axios(config[0], {
        method: config.method,
        data: ddd,
        params: params,
        headers: headers
    }).then(callback_success2)
        .catch(error_callback);
};

/**
 * 出现错误的处理
 * @param stringgg
 */
function error(stringgg) {
    console.error('d-error:',stringgg);
}

function success() {
    console.info(arguments);
}




/**
 * 获取配置信息
 * @param api_name
 * @returns {*}
 */
function apiconfig(api_name) {


    if (typeof api_config[api_name] =='object'){
        let config =api_config[api_name];

        if(typeof config.method == 'undefined') {
            config.method='get';
        }
        //设置执行完成后
        if(typeof config.interceptors == 'undefined') {
            config.interceptors=false;
        }


        if(typeof config.token == 'undefined') {
            config.token=true;
        }

        if(typeof config.enctype == 'undefined') {
            config.enctype='multipart/form-data';
        }

        return config;
    }
    return false;
}

export default ajax;
